package proxy

import (
	"go-proxy/common"
	"go-proxy/config"
	"net/http"
	"net/http/httptest"
	"time"
)

func handleResponse(server *config.ProxyServer, handle http.Handler, w http.ResponseWriter, r *http.Request) {
	startTime := time.Now() // 记录开始时间

	// 创建一个响应记录器
	rec := httptest.NewRecorder()
	handle.ServeHTTP(rec, r)

	common.LogDebug("请求后 url=", r.URL.String())

	// 计算并记录请求耗时
	duration := time.Since(startTime)
	// 记录响应信息
	common.AccessRespLogInfo(r, rec.Result(), duration.Milliseconds(), "http response")

	IncServerRequestCodeTotal(server, rec.Result().StatusCode)
	defer func() {
		HandleServerAfterMetrics(server)
		AddDownloadBytes(rec.Result().ContentLength)
		AddSlowRequestCostTime(server, r, duration.Milliseconds())
	}()

	// 将记录的响应写回原始响应
	for k, v := range rec.Result().Header {
		w.Header()[k] = v
	}
	w.WriteHeader(rec.Result().StatusCode)
	_, err := rec.Body.WriteTo(w)
	if err != nil {
		common.AccessLogErrorf(r, "write error server=%s err=%v", server.Name, err)
	}
}
